import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  Row,
  Col,
  Modal,
  Nav,
  Spinner,
  Tab,
  Form,
  Image,
  Button
} from 'react-bootstrap';
import { withRouter } from 'react-router-dom';
import $ from 'jquery';

import './less/userinfo.css';

import {
  URL,
  CODE
} from '../../config';
import {
  function_set_mine_avatar,
  function_set_nickname
} from '../../actions/member';
import {
  function_set_password,
  function_logout
} from '../../actions/passport';

class SetUserinfo extends Component {

  state = {
    passwordValidated: false,
    isPassword1Err: false,
    isPassword2Err: false,
    isLoading: false,
  }

  setPasswordValidated (passwordValidated) {
    this.setState({
      passwordValidated: passwordValidated
    })
  }

  handleSetPasswordSubmit (event) {
    let password1 = $(this.refs.password1).val();
    var regex = new RegExp('^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z_!@#$%^&*`~()-+=]+$)(?![0-9_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9_!@#$%^&*`~()-+=]{8,16}$');
    if (password1 === "" || !regex.test(password1)) {
      this.setState({ isPassword1Err: true });
      event.preventDefault();
      event.stopPropagation();
      return;
    } else {
      this.setState({ isPassword1Err: false });
    }
    let password2 = $(this.refs.password2).val();
    if (password2 !== password1) {
      this.setState({ isPassword2Err: true });
      event.preventDefault();
      event.stopPropagation();
      return;
    } else {
      this.setState({ isPassword2Err: false });
    }
    const form = event.currentTarget;
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    }
    this.setState({ isLoading: true });
    function_set_password(password1, result => {
      if (result.code === CODE.SUCCESS) {
        alert("密码更新成功，请重新登录");
        function_logout(this.props.dispatch);
        this.props.history.push(URL.login_page);
      } else {
        alert(result.message);
        this.setState({ isLoading: false });
      }
    });
    event.preventDefault();
    event.stopPropagation();
    this.setPasswordValidated(true);
  };

  handleFiles (event) {
    function_set_mine_avatar($(event.target)[0].files[0], (path) => {
      $(this.refs.avatarShow).attr("src", path);
    }, this.props.dispatch);
  }

  setNick () {
    let nickname = $(this.refs.nickname).val();
    function_set_nickname(nickname, () => {
      this.props.onHide();
    }, this.props.dispatch);
  }

  uploadAvatar () {
    document.getElementById("avatarInput").click();
  }

  render () {
    return (
      <Modal className="setUserInfo" show={this.props.showFlg} onHide={this.props.onHide.bind(this)}>
        <Modal.Header closeButton>
          <Modal.Title>个人设置</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Tab.Container defaultActiveKey="basic">
            <Row>
              <Col sm={3}>
                <Nav variant="tabs" className="flex-column">
                  <Nav.Item>
                    <Nav.Link eventKey="basic">基本设置</Nav.Link>
                  </Nav.Item>
                  <Nav.Item>
                    <Nav.Link eventKey="security">安全设置</Nav.Link>
                  </Nav.Item>
                </Nav>
              </Col>
              <Col sm={9}>
                <Tab.Content>
                  <Tab.Pane eventKey="basic">
                    <Form>
                      <Form.Group>
                        <Form.Label>头像</Form.Label>
                        <Image className="avatar" ref="avatarShow" src={this.props.account.avatar} roundedCircle />
                      </Form.Group>
                      <input type="file" accept="image/*" onChange={this.handleFiles.bind(this)} style={{ display: "none" }} id="avatarInput" />
                      <Button className="uploadBtn" size="sm" variant="primary" onClick={this.uploadAvatar.bind(this)}>
                        点击上传
                      </Button>
                      <Form.Group>
                        <Form.Label>昵称</Form.Label>
                        <Form.Control type="text" ref="nickname" placeholder="请输入昵称" defaultValue={this.props.account.nickname} />
                      </Form.Group>
                      <Button variant="primary" size="sm" onClick={this.setNick.bind(this)}>
                        更改基本信息
                      </Button>
                    </Form>
                  </Tab.Pane>
                  <Tab.Pane eventKey="security">
                    <Form className="passwordForm" noValidate validated={this.state.passwordValidated} onSubmit={this.handleSetPasswordSubmit.bind(this)}>
                      <Form.Group>
                        <Form.Label>重置密码</Form.Label>
                        <Form.Control required ref="password1" type="password" />
                        <Form.Control.Feedback type="invalid" style={{ display: this.state.isPassword1Err ? "block" : "none" }}>
                          至少6个字符，至少1个大写字母，1个小写字母和1个数字
                        </Form.Control.Feedback>
                      </Form.Group>
                      <Form.Group>
                        <Form.Label>再次输入密码</Form.Label>
                        <Form.Control required ref="password2" type="password" />
                        <Form.Control.Feedback type="invalid" style={{ display: this.state.isPassword2Err ? "block" : "none" }}>
                          再次输入的密码不一致
                        </Form.Control.Feedback>
                      </Form.Group>
                      <Button variant="primary" size="sm" type="submit"
                        disabled={this.state.isLoading ? true : false}>
                        {this.state.isLoading ?
                          <Spinner
                            as="span"
                            animation="border"
                            size="sm"
                            role="status"
                            aria-hidden="true"
                          />
                          : null}
                        重置密码
                      </Button>
                    </Form>
                  </Tab.Pane>
                </Tab.Content>
              </Col>
            </Row>
          </Tab.Container>
        </Modal.Body>
      </Modal>
    )
  }
}

function mapStateToProps (state) {
  return {
    account: state.account
  }
}

export default withRouter(connect(mapStateToProps)(SetUserinfo));